package com.subang.function.controller;

import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.subang.common.core.domain.entity.SysUser;
import com.subang.common.utils.SecurityUtils;
import com.subang.common.utils.StringUtils;
import com.subang.common.utils.uuid.UUID;
import com.subang.function.domain.SbUserStudyGroup;
import com.subang.function.service.ISbStudyMarkService;
import com.subang.function.service.ISbUserStudyGroupService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.subang.common.annotation.Log;
import com.subang.common.core.controller.BaseController;
import com.subang.common.core.domain.AjaxResult;
import com.subang.common.enums.BusinessType;
import com.subang.function.domain.SbStudyGroup;
import com.subang.function.service.ISbStudyGroupService;
import com.subang.common.utils.poi.ExcelUtil;

/**
 * 学习小组Controller
 * 
 * @author subei
 * @date 2025-03-29
 */
@RestController
@RequestMapping("/function/group")
public class SbStudyGroupController extends BaseController
{
    @Autowired
    private ISbStudyGroupService sbStudyGroupService;

    @Autowired
    private ISbUserStudyGroupService sbUserStudyGroupService;

    @Autowired
    private ISbStudyMarkService sbStudyMarkService;

    /**
     * 查询学习小组列表
     */
    @GetMapping("/list")
    public AjaxResult list(SbStudyGroup sbStudyGroup)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        
        // 1. 先获取用户所属的小组ID列表
        List<String> groupIds = sbUserStudyGroupService.selectGroupIdsByUserId(user.getUserId());
        
        // 2. 如果传入了查询条件，则按条件查询；否则查询用户所属的所有小组
        List<SbStudyGroup> list;
        if (sbStudyGroup != null && StringUtils.isNotBlank(sbStudyGroup.getGroupName())) {
            list = sbStudyGroupService.selectSbStudyGroupList(sbStudyGroup);
            // 过滤出用户所属的小组
            list = list.stream()
                    .filter(group -> groupIds.contains(group.getId()))
                    .collect(Collectors.toList());
        } else {
            // 直接查询用户所属的所有小组
            list = groupIds.stream()
                    .map(id -> sbStudyGroupService.selectSbStudyGroupById(id))
                    .collect(Collectors.toList());
        }
    
        // 3. 补充每个小组的成员信息和打卡信息
        for (SbStudyGroup group : list) {
            SbUserStudyGroup userStudyGroup = new SbUserStudyGroup();
            userStudyGroup.setGroupId(group.getId());
            List<SbUserStudyGroup> memberList = sbUserStudyGroupService.selectSbUserStudyGroupList(userStudyGroup);
            
            List<Long> userIds = memberList.stream()
                    .map(SbUserStudyGroup::getUserId)
                    .collect(Collectors.toList());
            Long todayMarkCount = sbStudyMarkService.countTodayMarkedUsersByIds(userIds);
            group.setTodayMarkCount(todayMarkCount);
            group.setMemberCount(Long.valueOf(memberList.size()));
        }

        return AjaxResult.success(list);
    }

    /**
     * 导出学习小组列表
     */
    @PreAuthorize("@ss.hasPermi('function:group:export')")
    @Log(title = "学习小组", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SbStudyGroup sbStudyGroup)
    {
        List<SbStudyGroup> list = sbStudyGroupService.selectSbStudyGroupList(sbStudyGroup);
        ExcelUtil<SbStudyGroup> util = new ExcelUtil<SbStudyGroup>(SbStudyGroup.class);
        util.exportExcel(response, list, "学习小组数据");
    }

    /**
     * 获取学习小组详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        SbStudyGroup sbStudyGroup = sbStudyGroupService.selectSbStudyGroupById(id);

        return success(sbStudyGroupService.selectSbStudyGroupById(id));
    }

    /**
     * 新增学习小组
     */
    @Log(title = "学习小组", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SbStudyGroup sbStudyGroup)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        sbStudyGroup.setCreatorId(user.getUserId());
        sbStudyGroup.setOwnerId(user.getUserId());

        String randomId = UUID.randomUUID().toString().replace("-", "");
        sbStudyGroup.setId(randomId);
        SbUserStudyGroup sbUserStudyGroup = new SbUserStudyGroup();
        sbUserStudyGroup.setUserId(user.getUserId());
        sbUserStudyGroup.setGroupId(randomId);
        sbUserStudyGroupService.insertSbUserStudyGroup(sbUserStudyGroup);
        return toAjax(sbStudyGroupService.insertSbStudyGroup(sbStudyGroup));
    }

    /**
     * 修改学习小组
     */
    @Log(title = "学习小组", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SbStudyGroup sbStudyGroup)
    {
        return toAjax(sbStudyGroupService.updateSbStudyGroup(sbStudyGroup));
    }

    /**
     * 删除学习小组
     */
    @Log(title = "学习小组", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(sbStudyGroupService.deleteSbStudyGroupByIds(ids));
    }

    @Log(title = "学习小组", businessType = BusinessType.DELETE)
    @PostMapping("/{id}")
    public AjaxResult removeSingle(@PathVariable String id)
    {
        AjaxResult ajaxResult = AjaxResult.success(sbStudyGroupService.deleteSbStudyGroupById(id));
        if(ajaxResult.isSuccess()){
            sbUserStudyGroupService.deleteSbUserStudyGroupByGroupId(id);
        }
        return ajaxResult;
    }
}
